<template>
  <div class="bg-white rounded-lg p-5 shadow-sm">
    <div class="flex justify-between items-center mb-4">
      <h2 class="text-lg font-medium">
        {{ t("system.overview.energyStatistics") }}
      </h2>
      <div class="text-sm text-gray-500">Latest: {{ latestTime }}</div>
    </div>

    <div class="grid grid-cols-[100px_1fr_2fr_2fr_1fr] gap-4">
      <!-- Today  Total  -->
      <div class="rounded-lg p-4">
        <div class="flex items-center gap-2 mb-3">
          <div class="text-yellow-500 w-6 h-6"></div>
          <div class="font-medium"></div>
        </div>

        <div class="mb-3">
          <div class="text-xs text-gray-500">&nbsp;</div>
          <div class="text-lg text-gray-500">Today</div>
        </div>

        <div>
          <div class="text-xs text-gray-500">&nbsp;</div>
          <div class="text-lg text-gray-500">Total</div>
        </div>
      </div>

      <!-- Solar -->
      <div class="bg-[#fefcf5] rounded-lg p-4">
        <div class="flex items-center gap-2 mb-3">
          <img :src="sun" alt="sun" class="w-6 h-6" />
          <div class="font-medium">{{ t("system.overview.solar") }}</div>
        </div>

        <div class="mb-3">
          <div class="text-xs text-gray-500">
            {{ t("system.overview.totalSolarGeneration") }}
          </div>
          <div class="flex items-center text-lg font-medium mt-2 text-black/70">
            <vue-countup-v3 :endVal="energyData.solar.totalGeneration.today" :options="countOptions" />
            kWh
          </div>
        </div>

        <div>
          <div class="text-xs text-gray-500">
            {{ t("system.overview.totalSolarGeneration") }}
          </div>
          <div class="flex items-center text-lg font-medium mt-2 text-black/70">
            <vue-countup-v3 :endVal="energyData.solar.totalGeneration.total" :options="countOptions" />
            kWh
          </div>
        </div>
      </div>

      <!-- Grid -->
      <div class="bg-[#fbfafe] rounded-lg p-4">
        <div class="flex items-center gap-2 mb-3">
          <img :src="grid" alt="grid" class="w-6 h-6" />
          <div class="font-medium">{{ t("system.overview.grid") }}</div>
        </div>

        <div class="grid grid-cols-2 gap-2 mb-3">
          <div>
            <div class="text-xs text-gray-500">
              {{ t("system.overview.exportToGrid") }}
            </div>
            <div class="flex items-center text-base font-medium mt-2 text-black/70">
              <vue-countup-v3 :endVal="energyData.grid.export.today" :options="countOptions" />
              kWh
            </div>
          </div>
          <div>
            <div class="text-xs text-gray-500">
              {{ t("system.overview.importFromGrid") }}
            </div>
            <div class="flex items-center text-base font-medium mt-2 text-black/70">
              <vue-countup-v3 :endVal="energyData.grid.import.today" :options="countOptions" />
              kWh
            </div>
          </div>
        </div>

        <div class="grid grid-cols-2 gap-2">
          <div>
            <div class="text-xs text-gray-500">
              {{ t("system.overview.exportToGrid") }}
            </div>
            <div class="flex items-center text-base font-medium mt-2 text-black/70">
              <vue-countup-v3 :endVal="energyData.grid.export.total" :options="countOptions" />
              kWh
            </div>
          </div>
          <div>
            <div class="text-xs text-gray-500">
              {{ t("system.overview.importFromGrid") }}
            </div>
            <div class="flex items-center text-base font-medium mt-2 text-black/70">
              <vue-countup-v3 :endVal="energyData.grid.import.total" :options="countOptions" />
              kWh
            </div>
          </div>
        </div>
      </div>

      <!-- Battery -->
      <div class="bg-[#f5fefc] rounded-lg p-4">
        <div class="flex items-center gap-2 mb-3">
          <img :src="battery" alt="battery" class="w-6 h-6" />
          <div class="font-medium">{{ t("system.overview.battery") }}</div>
        </div>

        <div class="grid grid-cols-2 gap-2 mb-3">
          <div>
            <div class="text-xs text-gray-500">
              {{ t("system.overview.exportToGrid") }}
            </div>
            <div class="flex items-center text-base font-medium mt-2 text-black/70">
              <vue-countup-v3 :endVal="energyData.battery.export.today" :options="countOptions" />
              kWh
            </div>
          </div>
          <div>
            <div class="text-xs text-gray-500">
              {{ t("system.overview.importFromGrid") }}
            </div>
            <div class="flex items-center text-base font-medium mt-2 text-black/70">
              <vue-countup-v3 :endVal="energyData.battery.import.today" :options="countOptions" />
              kWh
            </div>
          </div>
        </div>

        <div class="grid grid-cols-2 gap-2">
          <div>
            <div class="text-xs text-gray-500">
              {{ t("system.overview.exportToGrid") }}
            </div>
            <div class="flex items-center text-base font-medium mt-2 text-black/70">
              <vue-countup-v3 :endVal="energyData.battery.export.total" :options="countOptions" />
              kWh
            </div>
          </div>
          <div>
            <div class="text-xs text-gray-500">
              {{ t("system.overview.importFromGrid") }}
            </div>
            <div class="flex items-center text-base font-medium mt-2 text-black/70">
              <vue-countup-v3 :endVal="energyData.battery.import.total" :options="countOptions" />
              kWh
            </div>
          </div>
        </div>
      </div>

      <!-- Home -->
      <div class="bg-[#f8fdff] rounded-lg p-4">
        <div class="flex items-center gap-2 mb-3">
          <img :src="home" alt="home" class="w-6 h-6" />
          <div class="font-medium">{{ t("system.overview.home") }}</div>
        </div>

        <div class="mb-3">
          <div class="text-xs text-gray-500">
            {{ t("system.overview.totalSolarGeneration") }}
          </div>
          <div class="flex items-center text-lg font-medium mt-2 text-black/70">
            <vue-countup-v3 :endVal="energyData.home.totalConsumption.today" :options="countOptions" />
            kWh
          </div>
        </div>

        <div>
          <div class="text-xs text-gray-500">
            {{ t("system.overview.totalSolarGeneration") }}
          </div>
          <div class="flex items-center text-lg font-medium mt-2 text-black/70">
            <vue-countup-v3 :endVal="energyData.home.totalConsumption.total" :options="countOptions" />
            kWh
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import sun from "../../assets/sun.png";
import grid from "../../assets/grid.png";
import battery from "../../assets/battery.png";
import home from "../../assets/home.png";
import VueCountupV3 from "vue-countup-v3";
import { useI18n } from "@/composables/useI18n";
import { energyAppApi } from "@/api/business";

const { t } = useI18n();
const route = useRoute();

const props = defineProps({
  latestTime: {
    type: String,
    default: "2025-02-12 19:20 (UTC+8:00)"
  },
  systemId: {
    type: String,
    required: true
  }
});

// 展示数据模型（占位）
const energyData = ref<any>({
  solar: { totalGeneration: { today: 0, total: 0 } },
  grid: {
    export: { today: 0, total: 0 },
    import: { today: 0, total: 0 }
  },
  battery: {
    export: { today: 0, total: 0 },
    import: { today: 0, total: 0 }
  },
  home: { totalConsumption: { today: 0, total: 0 } }
});

// CountUp配置
const countOptions = {
  useEasing: true,
  useGrouping: true,
  separator: ",",
  decimal: ".",
  decimalPlaces: 2,
  prefix: "",
  suffix: ""
};

// 对接真实 /as/tdengine/hems/energy：仅取最后一条记录原值
const loadEnergySummary = async () => {
  const now = new Date();
  const pad = (n: number) => String(n).padStart(2, "0");
  const fmt = (d: Date) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
  const start = new Date(now);
  start.setHours(0, 0, 0, 0);

  // hemsId 从路由获取并转数字
  const hemsIdNumber = Number(String(route.query.hemsId || props.systemId || 0));
  if (!hemsIdNumber) return;

  const body: any = {
    hemsId: hemsIdNumber,
    deviceId: 0,
    beginDate: fmt(start),
    endDate: fmt(now),
    startDate: fmt(start),
    endStrDate: fmt(now),
    type: 0,
    energyType: 0,
    format: 0
  };

  try {
    // 真实能耗接口
    const resp: any = await energyAppApi.getSolarFlowAllList(body);

    if ((resp?.code === 0 || resp?.code === 200) && resp?.data) {
      // 兼容对象/数组，取最后一条记录展示
      const rows = (Array.isArray(resp.data) ? resp.data : [resp.data]).filter(Boolean);
      const d: any = rows.length ? rows[rows.length - 1] : {};

      energyData.value = {
        solar: {
          totalGeneration: {
            today: Number(d.solar ?? d.pv ?? 0),
            total: Number(d.solar ?? d.pv ?? 0)
          }
        },
        grid: {
          export: {
            today: Number(d.acOutputTotal ?? d.outputToGrid ?? 0),
            total: Number(d.acOutputTotal ?? d.outputToGrid ?? 0)
          },
          import: {
            today: Number(d.gridInputTotal ?? d.gridInput ?? 0),
            total: Number(d.gridInputTotal ?? d.gridInput ?? 0)
          }
        },
        battery: {
          export: {
            today: Number(d.batteryOutput ?? 0),
            total: Number(d.batteryOutput ?? 0)
          },
          import: {
            today: Number(d.batteryInput ?? 0),
            total: Number(d.batteryInput ?? 0)
          }
        },
        home: {
          totalConsumption: {
            today: Number(d.home ?? d.outputToHome ?? 0),
            total: Number(d.home ?? d.outputToHome ?? 0)
          }
        }
      };
    }
  } catch (e) {
    console.warn("loadEnergySummary failed", e);
  }
};

onMounted(loadEnergySummary);
</script>
